package config

import (
	runtime "github.com/banzaicloud/logrus-runtime-formatter"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gopkg.in/natefinch/lumberjack.v2"
	"time"
)

var (
	useTestData = false
	timer       *time.Timer
)

func SetUseTestData(enable bool) {
	if timer != nil {
		_ = timer.Stop()
	}

	if enable {
		// 开启定时器
		timer = time.AfterFunc(10*time.Minute, func() {
			log.Infof("关闭使用测试数据！")
			useTestData = false
		})
	}

	useTestData = enable
}

func GetUseTestData() bool {
	return useTestData
}

func Init() {
	// init config
	if err := LoadCfg(); err != nil {
		panic(err)
	}

	// log rotation
	logger := lumberjack.Logger{
		Filename:   viper.GetString("log.location"),
		MaxSize:    viper.GetInt("log.maxSize"),
		MaxBackups: viper.GetInt("log.maxBackups"),
		MaxAge:     viper.GetInt("log.maxAge"),
	}

	formatter := runtime.Formatter{ChildFormatter: &log.TextFormatter{
		FullTimestamp: true,
	}}
	formatter.Line = true
	log.SetFormatter(&formatter)
	log.SetLevel(log.DebugLevel)
	log.SetOutput(&logger)

	// mysql
	InitDB()
}

func LoadCfg() error {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("../..")
	viper.AddConfigPath("..")
	viper.AddConfigPath(".")
	if err := viper.ReadInConfig(); err != nil {
		return err
	}

	return nil
}

func GetAppId() string {
	return viper.GetString("appid")
}

func GetAppSecret() string {
	return viper.GetString("appSecret")
}

func GetSecret() string {
	return viper.GetString("encrypt.jwt_secret")
}

func GetSingle() bool {
	return viper.GetString("single") == "true"
}

func GetAlgorithmUrl() string {
	return viper.GetString("algorithm.url")
}

func GetSportPredictUrl() string {
	return viper.GetString("algorithm.sportpredict")
}

func GetPrescriptionUrl() string {
	return viper.GetString("algorithm.prescription")
}

func GetAgentUrl() string {
	return viper.GetString("algorithm.agent")
}

func GetCsiiUrl() string {
	return viper.GetString("algorithm.csii")
}

func InitForTest() {
	// init config
	if err := LoadCfg(); err != nil {
		panic(err)
	}

	// mysql
	InitDB()
}
